package com.zheng.api.server.service.command;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zheng.api.common.constant.ApiConstant;
import com.zheng.api.common.constant.ApiResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.service.ApiServerUmbrellaService;
import com.zheng.api.server.service.WxTemplateService;
import com.zheng.api.server.service.base.um.Base4UmbrellaService;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaMachineNotify;
import com.zheng.api.server.service.mq.um.Mq4UmbrellaWechatappNotify;
import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumption;
import com.zheng.business.dao.model.BusinessOrderUmbrellaConsumptionExample;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.DateUtil;
import com.zheng.common.util.GpsUtil;
import com.zheng.common.util.JsonUtil;
import com.zheng.common.util.RedisUtil;
import com.zheng.umbrella.common.constant.UmbrellaConstant;
import com.zheng.umbrella.dao.model.*;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareManageLogService;
import com.zheng.umbrella.rpc.api.UmbrellaRuleSpecialconfigDetailService;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 伞机指令业务处理
 * @author lvb
 * @date 2017-09-05
 * @version V1.0
 * @Copyright: www.bjs-tech.com
 */
@Service
public class MachineBusiness4CommandServiceV1 extends Base4UmbrellaService implements MachineBusinessCommandInterface {

    private static final Logger LOGGER = LoggerFactory.getLogger(MachineBusiness4CommandServiceV1.class);
    @Autowired
    ApiServerUmbrellaService apiServerUmbrellaService;
    @Autowired
    Mq4UmbrellaMachineNotify mq4UmbrellaMachineNotify;
    @Autowired
    Mq4UmbrellaWechatappNotify mq4UmbrellaWechatappNotify;
    @Autowired
    UpmsSystemParamService upmsSystemParamService;
    @Autowired
    UmbrellaHardwareManageLogService umbrellaHardwareManageLogService;
    @Autowired
    UmbrellaRuleSpecialconfigDetailService umbrellaRuleSpecialconfigDetailService;
    @Autowired
    WxTemplateService wxTemplateService;

    /**
     * 缓存模块前缀
     */
    @Value("${Redis.CacheModule}")
    private String cacheModule;

    /**
     * 设备状态上报【20002】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20002(String command,String machineCode, int code, String message, JSONObject recvData) {
        /**
         {
         "command": "20002",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "serialNo": "20180929100020001",
         "longitude": 23.21,
         "latitude": 113.33,
         "status": 2,
         "faultStatus": 0,
         "faultStatusdesc": "主板温度高于50度",
         "electricQuantity": 60.3
         }
         }
         */
        try{
            if (code == ApiResultConstant.SUCCESS.code) {
                //String machineCode = recvData.getString("machineCode");
                UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                if (umbrellaHardwareMachine != null) {
                    int status = umbrellaHardwareMachine.getStatus();

                    //GPS修正为火星坐标系（Gcj02）
                    double longitude = recvData.getBigDecimal("longitude")==null?0:recvData.getBigDecimal("longitude").doubleValue();
                    double latitude = recvData.getBigDecimal("latitude")==null?0:recvData.getBigDecimal("latitude").doubleValue();
                    double[] latlong = GpsUtil.gps84_To_Gcj02(latitude,longitude);
                    BigDecimal  newLat= new BigDecimal(latlong[0]);
                    BigDecimal  newLong= new BigDecimal(latlong[1]);
                    //
                    //更新内容
                    UmbrellaHardwareMachine updateMachine = new UmbrellaHardwareMachine();
                    //状态是手工关闭和正常运营的进行不同更新
                    if (status != UmbrellaConstant.UM_MACHINE_STATUS_4) {
                        int reportStatus = recvData.getInteger("status");
                        reportStatus = (reportStatus==UmbrellaConstant.UM_MACHINE_STATUS_2?UmbrellaConstant.UM_MACHINE_STATUS_2:UmbrellaConstant.UM_MACHINE_STATUS_1);
                        updateMachine.setStatus(reportStatus);
                        updateMachine.setFaultstatus(recvData.getInteger("faultStatus"));
                        updateMachine.setElectricquantity(recvData.getBigDecimal("electricQuantity"));
                        updateMachine.setLongitudeReport(newLong);
                        updateMachine.setLatitudeReport(newLat);
                        if(umbrellaHardwareMachine.getLatitude()==null || umbrellaHardwareMachine.getLatitude().equals(BigDecimal.ZERO)){
                            updateMachine.setLongitude(newLong);
                            updateMachine.setLatitude(newLat);
                        }
                    } else {
                        updateMachine.setFaultstatus(recvData.getInteger("faultStatus"));
                        updateMachine.setElectricquantity(recvData.getBigDecimal("electricQuantity"));
                        updateMachine.setLongitudeReport(newLong);
                        updateMachine.setLatitudeReport(newLat);
                        if(umbrellaHardwareMachine.getLatitude()==null || umbrellaHardwareMachine.getLatitude().equals(BigDecimal.ZERO)){
                            updateMachine.setLongitude(newLong);
                            updateMachine.setLatitude(newLat);
                        }
                    }
                    updateMachine.setLasttimeReport(DateUtil.getNowDate());
                    //更新条件
                    UmbrellaHardwareMachineExample queryExample = new UmbrellaHardwareMachineExample();
                    UmbrellaHardwareMachineExample.Criteria queryCriteria = queryExample.createCriteria();
                    //未删除
                    queryCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                    //状态正常
                    queryCriteria.andCodeEqualTo(machineCode);
                    int ret = super.updateUmbrellaHardwareMachine(updateMachine, queryExample);
                }
            }
        }catch (Exception e){
            LOGGER.error("设备状态上报【{}】异常,machineCode={},code={},message={}",machineCode,command,code,message,recvData.toJSONString(),e);
        }
        return null;
    }
    /**
     * 通信连接建立失败通知【20004】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20004(String command,String machineCode, int code, String message, JSONObject recvData){
        //通信连接建立失败通知【20004】,见ApiCommonService.notify
        return null;
    }
    /**
     * 扫码借伞-雨伞识别结果上报【20101】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20101(String command,String machineCode, int code, String message, JSONObject recvData){
       /**
         {
         "command": "20101",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "orderNo": "20181101100020001",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"
         },
         "status": 6,
         "pathCode": "path222222",
         "pathNumber": 1,
         "chipNumber": "111111"
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code,ApiResultConstant.FAILED.message,ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30101,machineCode,dataInfo);
        int account = 0;
        try {
            String orderNo = recvData.getString("orderNo");
            int status = recvData.getInteger("status");
            String pathCode = recvData.getString("pathCode");
            int pathNumber = recvData.getInteger("pathNumber");
            String chipNumber = recvData.getString("chipNumber");
            dataInfo.put("orderNo", orderNo);
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            dataInfo.put("faultStatus",JsonUtil.getInteger(recvData,"status"));
            account = recvData.getJSONObject("dataPackage").getInteger("account");

            //查询订单是否存在
            BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaConsumptionByOrderNo(orderNo);
            if (businessOrderUmbrellaConsumption != null) {
                account = businessOrderUmbrellaConsumption.getUserid();
                /**
                 {
                 "command": "10102",
                 "machineCode": "2018092700001",
                 "code": 1,
                 "message": "",
                 "data": {
                 "orderNo": "20181101100020001",
                 "status": 6,
                 "pathCode": "path222222",
                 "pathNumber": 1,
                 "chipNumber": "111111",
                 "dataPackage": {
                 "account": 10000004,
                 "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
                 }
                 }
                 }
                 */
                //组装更新借伞基础信息
                BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                updateConsumption.setChipNumber(chipNumber);
                updateConsumption.setPathNumber(pathNumber);
                updateConsumption.setPathCode(pathCode);
                updateConsumption.setFaultstatus(status);
                //更新条件
                BusinessOrderUmbrellaConsumptionExample consumptionExample = new BusinessOrderUmbrellaConsumptionExample();
                BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
                consumptionCriteria.andOrdernoEqualTo(orderNo);
                if (code == ApiResultConstant.SUCCESS.code) {
                    /** 1 机器码不正确 2 指令不正确  3 机器正在工作中  4 启动红外失败 5 RFID读头启动失败 6 RFID读取雨伞成功  7 RFID读取雨伞超时 */
                    if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_6 || status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_7){

                        UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = null;
                        if(StringUtils.isNotEmpty(chipNumber)) {
                            umbrellaHardwareUmbrella = super.baseSelectUmbrellaHardwareUmbrellaNoCache(chipNumber);
                        }
                        String secondPath = cacheModule + ":" + ApiConstant.UMBRELLA_MACHINE_BORROW_SECONDFALG + ":" + businessOrderUmbrellaConsumption.getUserid();
                        String firstOrderNo = RedisUtil.get(secondPath);

                        //第一次雨伞识别成功并且是我司雨伞、第二次无论是否我司雨伞
                        if ((umbrellaHardwareUmbrella != null&&status==ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_6)
                                || (StringUtils.isNotEmpty(firstOrderNo) && status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_7)) {
                            //识别雨伞id成功，先保存雨伞id到订单
                            if(umbrellaHardwareUmbrella != null) {
                                updateConsumption.setUmbrellaCode(umbrellaHardwareUmbrella.getCode());
                                updateConsumption.setCostprice(umbrellaHardwareUmbrella.getCostprice());
                                updateConsumption.setMarketprice(umbrellaHardwareUmbrella.getMarketprice());
                                super.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionExample);
                            }
                            JSONObject machineDataInfo = new JSONObject();
                            machineDataInfo.put("orderNo", recvData.getString("orderNo"));
                            machineDataInfo.put("pathCode", recvData.getString("pathCode"));
                            machineDataInfo.put("pathNumber", recvData.getIntValue("pathNumber"));
                            machineDataInfo.put("chipNumber", chipNumber);
                            machineDataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
                            ApiResult machineNotifyInfo = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message,
                                    ApiConstant.UMBRELLA_MACHINE_COMMAND_10102, machineCode, machineDataInfo);
                            //通知设备开启出伞模式
                            mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineNotifyInfo), machineCode);

                            //组装返回数据
                            result.setCode(ApiResultConstant.SUCCESS.code);
                            result.setMessage(ApiResultConstant.SUCCESS.message);
                            result.setData(dataInfo);
                        }else{
                            LOGGER.error("扫码借伞-雨伞识别结果上报【20101】第一次借伞识别失败,machineCode={},commanddata={}",machineCode,recvData.toJSONString());
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                            //第一次不是我司雨伞、超时读取不到雨伞id，均设置二次借伞标识
                            int timeout = 10;
                            try {
                                timeout = Integer.parseInt(upmsSystemParamService.querySystemParamValueByParam_key("UMBRELLA_MACHINE_BORROW_SECONDTIME"));
                            } catch (Exception e) {
                                timeout = 10;
                            }
                            RedisUtil.set(secondPath, orderNo, timeout);

                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                            result.setData(dataInfo);
                            //更新订单为失败
                            updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_1);
                            super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionExample);
                        }
                    }else{
                        LOGGER.error("扫码借伞-雨伞识别结果上报【20101】伞机业务处理失败,machineCode={},commanddata={}",machineCode,recvData.toJSONString());
                        result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                        result.setData(dataInfo);
                        //更新订单为失败
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_1);
                        super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionExample);
                    }
                }else{
                    LOGGER.error("扫码借伞-雨伞识别结果上报【20101】伞机业务处理失败,machineCode={},commanddata={}",machineCode,recvData.toJSONString());
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                    result.setData(dataInfo);
                    //更新订单为失败
                    updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_1);
                    super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionExample);
                }
            } else {
                LOGGER.error("扫码借伞-雨伞识别结果上报【20101】订单不存在,machineCode={},commanddata={}",machineCode,recvData.toJSONString());
                result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                result.setData(dataInfo);
            }
        }catch (Exception e){
            LOGGER.error("扫码借伞-雨伞识别结果上报异常,machineCode={},code={},message={},commanddata={}",machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage(ApiResultConstant.FAILED.message);
            result.setData(dataInfo);
        }
        //使用mq消息将借伞处理失败通知小程序
        if(result.getCode() != ApiResultConstant.SUCCESS.code && account>0 ){
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 扫码借伞-出伞结果上报【20102】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20102(String command,String machineCode, int code, String message, JSONObject recvData){
        /**
         {
         "command":"20102",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "orderNo": "20181101100020001",
         "status": 9,
         "pathCode": "path222222",
         "pathNumber": 1,
         "chipNumber": "111111",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"
         }
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code,ApiResultConstant.FAILED.message,ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30101,machineCode,dataInfo);
        int account = 0;
        try {
            dataInfo.put("orderNo", recvData.getString("orderNo"));
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            account = recvData.getJSONObject("dataPackage").getInteger("account");
            String orderNo = recvData.getString("orderNo");
            String pathCode = recvData.getString("pathCode");
            int pathNumber = recvData.getInteger("pathNumber");
            String chipNumber = recvData.getString("chipNumber");
            int status = recvData.getInteger("status");
            dataInfo.put("faultStatus", status);
            //查询订单是否存在
            BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaConsumptionByOrderNo(orderNo);
            if (businessOrderUmbrellaConsumption != null) {
                account = businessOrderUmbrellaConsumption.getUserid();
                //组装更新借伞基础信息
                BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                updateConsumption.setFaultstatus(status);
                if(StringUtils.isNotEmpty(chipNumber)) {
                    updateConsumption.setChipNumber(chipNumber);
                }
                updateConsumption.setPathCode(pathCode);
                updateConsumption.setPathNumber(pathNumber);
                //更新条件
                BusinessOrderUmbrellaConsumptionExample consumptionExample = new BusinessOrderUmbrellaConsumptionExample();
                BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
                consumptionCriteria.andOrdernoEqualTo(orderNo);

                //伞机业务处理成功
                if (code == ApiResultConstant.SUCCESS.code) {
                    /** 1 机器码不正确 2 指令不正确  3 机器正在工作中  4 启动红外失败 5 RFID读头启动失败 6 RFID读取雨伞成功  7 RFID读取雨伞超时 */
                    //红外被切断
                    if (status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9) {
                        //借伞成功
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3);
                        Date time = DateUtil.getNowDate();
                        updateConsumption.setBegintime(time);
                        //超时自动结算
                        //租金封顶金额
                        int autoCloseDate = 0;
                        BigDecimal feeLimitAmount = BigDecimal.ZERO;
                        try {
                            //总开关
                            String masterSwitch = upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_AUTOCLOSE_DAY");
                            if("true".equals(masterSwitch)){
                                //超时自动结算
                                UmbrellaRuleSpecialconfigDetail agentSpecialConfig = super.baseSelectAgentSpecialConfig(businessOrderUmbrellaConsumption.getAgentid(),Constant.UM_ORDER_TIMEOUT_AUTOCLOSE);
                                if(agentSpecialConfig != null){
                                    if(Constant.CONST_ENABLE == agentSpecialConfig.getStatus()){
                                        autoCloseDate = Integer.parseInt(agentSpecialConfig.getValue());
                                    }
                                }
                            }
                            //租金封顶金额
                            // (启用后，借伞订单计费将启用计费上限（租金规则配置的封顶金额大于0时，以租金规则配置的封顶金额为准，否则以个性规则配置的封顶金额为准；
                            // 如果两者均配置为小于等于0，则按正常计费）。)
                            UmbrellaRuleSpecialconfigDetail agentSpecialConfig = super.baseSelectAgentSpecialConfig(businessOrderUmbrellaConsumption.getAgentid(),Constant.UM_ORDER_FEELIMIT);
                            if(agentSpecialConfig != null){
                                if(Constant.CONST_ENABLE == agentSpecialConfig.getStatus()){
                                    double spFeeLimit = 0;
                                    if(agentSpecialConfig.getValue()!=null) {
                                        spFeeLimit = Double.valueOf(agentSpecialConfig.getValue());
                                    }
                                    double rentFeeLimit = super.baseSelectUmbrellaRuleRentNoCache(businessOrderUmbrellaConsumption.getRentRuleId(),false).getFeelimit().doubleValue();
                                    spFeeLimit  = super.calculateAmountByCapping(rentFeeLimit,spFeeLimit,agentSpecialConfig.getStatus());
                                    feeLimitAmount = new BigDecimal(spFeeLimit);
                                }
                            }
                        } catch (Exception e) {
                            LOGGER.error("获取代理个性规则异常,agentId={},code={}",businessOrderUmbrellaConsumption.getAgentid(),Constant.UM_ORDER_TIMEOUT_AUTOCLOSE,e);
                            autoCloseDate = 0;
                        }
                        if(autoCloseDate>0) {
                            updateConsumption.setAutoendtime(DateUtil.addDate(time, autoCloseDate));
                        }else{
                            updateConsumption.setAutoendtime(null);
                        }
                        updateConsumption.setLimitamount(feeLimitAmount);

                        //查询雨伞信息，赋予市场价等
                        if(StringUtils.isNotEmpty(chipNumber)) {
                            UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = super.baseSelectUmbrellaHardwareUmbrellaNoCache(chipNumber);
                            if (umbrellaHardwareUmbrella != null) {
                                updateConsumption.setUmbrellaCode(umbrellaHardwareUmbrella.getCode());
                                updateConsumption.setCostprice(umbrellaHardwareUmbrella.getCostprice());
                                updateConsumption.setMarketprice(umbrellaHardwareUmbrella.getMarketprice());
                            }
                        }
                        int ret = super.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionExample);
                        if(ret>0) {
                            //规避重复指令问题导致的伞机及伞道余量和用户借伞量的多算问题
                            if(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3 != businessOrderUmbrellaConsumption.getStatus()) {
                                //更新伞机及伞道余量
                                super.updateUmbrellaMachineAndPathRemainder(machineCode, pathCode, pathNumber, -1);
                                //更新雨伞为借出状态
                                if (StringUtils.isNotEmpty(chipNumber)) {
                                    super.updateUmbrellaHardwareUmbrellaStatus(chipNumber, UmbrellaConstant.UM_UMBRELLA_STATUS_3,null);
                                }
                                //更新用户借伞状态
                                super.updateUserAccountUmbrellaStatus(account, 1);
                                //发送借伞成功服务提醒(微信)
                                wxTemplateService.miniAppTemplatePush(orderNo,1);
                            }

                            result.setCode(ApiResultConstant.SUCCESS.code);
                            result.setMessage(ApiResultConstant.SUCCESS.message);
                            result.setData(dataInfo);

                            //结算其他借出或归还失败的订单
                            if(StringUtils.isNotEmpty(chipNumber)) {
                                BusinessOrderUmbrellaConsumption otherConsumption = super.baseSelectBusinessOrderUmbrellaUnReturnByChipNumber(chipNumber, true, orderNo);
                                if (otherConsumption != null) {
                                    //更新用户借伞状态,需先更新用户状态，否则预付金无法退还
                                    super.updateUserAccountUmbrellaStatus(otherConsumption.getUserid(), -1);
                                    //结算计费
                                    apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(otherConsumption.getOrderno(), true, false, false);
                                }
                            }
                        }else{
                            LOGGER.error("扫码借伞-出伞结果上报红外切断成功，但更新数据库异常,machineCode={},code={},message={},commandata={}",
                                    machineCode,code,message,recvData.toJSONString());
                        }
                    } else {
                        if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.code) {
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.message);
                        }else if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.code){
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.message);
                        }else if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.code){
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.message);
                        }else {
                            result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                            result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                        }
                        result.setData(dataInfo);
                        //更新订单为失败
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_1);
                        super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionExample);
                    }
                } else {
                    //订单不存在，如果上报红外切断也要变更伞机伞量
                    if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        //更新伞机及伞道余量
                        super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,-1);
                    }
                    result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                    result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                    result.setData(dataInfo);
                    //更新订单为失败
                    updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_1);
                    super.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionExample);
                }
                result.setData(dataInfo);
            } else {
                //订单不存在，如果上报红外切断也要变更伞机伞量
                if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                    //更新伞机及伞道余量
                    super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,-1);
                }
                LOGGER.error("扫码借伞-出伞结果上报【20102】订单不存在,machineCode={},commanddata={}",machineCode,recvData.toJSONString());
                result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                result.setData(dataInfo);
            }
        }catch (Exception e){
            LOGGER.error("扫码借伞-出伞结果上报异常,machineCode={},code={},message={},commandata={}",machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage(ApiResultConstant.FAILED.message);
            result.setData(dataInfo);
        }
        //使用mq消息将借伞结果通知小程序
        if(account>0) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 扫码还伞-还伞结果上报【20105】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20105(String command,String machineCode, int code, String message, JSONObject recvData){

        /**
         {
         "command":"20105",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "orderNo": "20180929100020001",
         "status": 9,
         "pathCode": "path222222",
         "pathNumber": 1,
         "chipNumber": "111111",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"
         }
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30201,machineCode, dataInfo);
        Integer account = 0;
        //上传的伞id集合
        List<String> resultChipNumList = new ArrayList<String>();
        //订单的伞id
        String orderChipNumber = "";

        try {
            dataInfo.put("orderNo", recvData.getString("orderNo"));
            dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));
            String orderNo = JsonUtil.getString(recvData,"orderNo");
            String pathCode = JsonUtil.getString(recvData,"pathCode");
            int pathNumber = JsonUtil.getInteger(recvData,"pathNumber");
            String chipNumber = JsonUtil.getString(recvData,"chipNumber");
            Integer status = JsonUtil.getInteger(recvData,"status");
            JSONObject dataPackage = JsonUtil.getJSONObject(recvData,"dataPackage");
            account = JsonUtil.getInteger(dataPackage,"account");
            dataInfo.put("faultStatus", status);

            if(StringUtils.isNotEmpty(chipNumber)){
                CollectionUtils.addAll(resultChipNumList,chipNumber.split(ApiConstant.CHIP_NUMBER_SEPARATOR));
            } else {
                resultChipNumList.add("");
            }

            if (ApiResultConstant.FAILED.code == code){//伞机返回错误状态
                result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                result.setData(dataInfo);
            }else{
                ////伞机业务处理成功 成功状态
                //查询订单
                BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaConsumptionByOrderNo(orderNo);
                //订单存在
                if (businessOrderUmbrellaConsumption != null) {
                    account = businessOrderUmbrellaConsumption.getUserid();
                    orderChipNumber = businessOrderUmbrellaConsumption.getChipNumber();
                    if (StringUtil.isEmpty(orderChipNumber)){
                        orderChipNumber = "";
                    }
                            /**
                             * 1 机器码不正确
                             * 2 指令不正确
                             * 3 机器正在工作中
                             * 4 启动红外失败
                             * 5 RFID读头启动失败
                             * 6 RFID读取雨伞成功
                             * 7 RFID读取雨伞超时
                             * 8 红外切断超时
                             * 9 红外切断成功
                             */
                            //组装更新订单信息
                            //查询雨伞信息,判断是否我司雨伞
//                            if(chipNumber == null){
//                                chipNumber = "";
//                            }
//                            String borrowChipNumber = businessOrderUmbrellaConsumption.getChipNumber()==null?"":businessOrderUmbrellaConsumption.getChipNumber();
                            //是否算还伞
//                            boolean isComplete = chipNumber.equals(borrowChipNumber);
                            //是否算还伞
                            boolean isComplete = resultChipNumList.contains(orderChipNumber);
                            /**
                            //是否标识特殊客户
                            boolean isSpecial = false;
                            //判断借伞时雨伞id和当前还伞id同时为空或相同
                            if(chipNumber.equals(borrowChipNumber))
                            {
                                isComplete = true;
                            }else{
                                //判断归还的雨伞是否我司雨伞
                                UmbrellaHardwareUmbrella borrowUmbrella = super.baseSelectUmbrellaHardwareUmbrellaNoCache(borrowChipNumber);
                                UmbrellaHardwareUmbrella returnUmbrella = super.baseSelectUmbrellaHardwareUmbrellaNoCache(chipNumber);
                                //借为我司雨伞
                                if (borrowUmbrella != null) {
                                    //还时不是我司雨伞
                                    if(returnUmbrella == null )
                                    {
                                        //还雨伞id不为空
                                        if(StringUtils.isNotEmpty(chipNumber)){
                                            isComplete = false;
                                        }else{
                                            isComplete = true;
                                            isSpecial = true;
                                        }
                                    }else{
                                        isComplete = true;
                                    }
                                    //借时不是我司雨伞
                                } else{
                                    //还时不是我司雨伞
                                    if(returnUmbrella == null ){
                                        //还时雨伞id为空或者id相等
                                        if(StringUtils.isEmpty(chipNumber) || chipNumber.equals(borrowChipNumber)){
                                            isComplete = true;
                                        }else{
                                            isComplete = false;
                                            isSpecial = true;
                                        }
                                    }else{
                                        isComplete = true;
                                    }
                                }
                            }*/
                            Date time = DateUtil.getNowDate();
                            BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                            //返回状态为 9 为成功状态
                            if (isComplete && ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9.equals(status)) {
                                //还伞成功
                                updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5);
                            } else {
                                //还伞失败
                                updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
                            }
                            //查询伞机
                            UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                            if (umbrellaHardwareMachine != null) {
                                updateConsumption.setReturnAdress(umbrellaHardwareMachine.getAddress());
                            }
                            updateConsumption.setEndtime(time);
                            updateConsumption.setFaultstatus(status);
                            updateConsumption.setReturnMachineId(machineCode);
                            updateConsumption.setReturnPathCode(pathCode);
                            updateConsumption.setReturnPathNumber(pathNumber);
                            updateConsumption.setReturnChipNumber(chipNumber);
                            BusinessOrderUmbrellaConsumptionExample consumptionQueryExample = new BusinessOrderUmbrellaConsumptionExample();
                            BusinessOrderUmbrellaConsumptionExample.Criteria consumptionQueryCriteria = consumptionQueryExample.createCriteria();
                            //orderNo
                            consumptionQueryCriteria.andOrdernoEqualTo(orderNo);
                            int ret = super.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionQueryExample);
                            if(ret>0) {
                                //组装返回信息，用于通知用户端
                                if (ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9.equals(status)) {

                                    //规避重复指令问题导致的伞机及伞道余量和用户借伞量的多算问题
                                    if(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5 != businessOrderUmbrellaConsumption.getStatus() && BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6 != businessOrderUmbrellaConsumption.getStatus()) {
                                        //更新伞机及伞道余量
                                        super.updateUmbrellaMachineAndPathRemainder(machineCode, pathCode, pathNumber, 1);
                                        //更新雨伞为/空闲/归还状态
                                        if(StringUtils.isNotEmpty(chipNumber)) {
                                            super.updateUmbrellaHardwareUmbrellaStatus(chipNumber, UmbrellaConstant.UM_UMBRELLA_STATUS_2,machineCode);
                                        }
                                        if(isComplete){
                                            //更新用户借伞状态
                                            super.updateUserAccountUmbrellaStatus(account, -1);
                                            //结算计费
                                            apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(orderNo, true, false,false);
                                        }
                                    }
                                    result.setCode(ApiResultConstant.SUCCESS.code);
                                    result.setMessage("还伞成功");
                                } else {
                                    if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.code) {
                                        result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.code);
                                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL7.message);
                                    }else if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.code){
                                        result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.code);
                                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL8.message);
                                    }else if(status == ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.code){
                                        result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.code);
                                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL12.message);
                                    }else {
                                        result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                                        result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                                    }
                                }
                            }
                            result.setData(dataInfo);
                } else { //业务订单不存在
                    //订单不存在，如果上报红外切断也要变更伞机伞量
                    if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        //更新伞机及伞道余量
                        super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,1);
                    }
                    result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            LOGGER.error("扫码还伞-还伞结果上报【{}】异常,machineCode={},code={},message={},commandata={}",command,machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage("还伞失败");
            result.setData(dataInfo);
        }
        for(String chipId : resultChipNumList){
            if(!orderChipNumber.equals(chipId) && StringUtils.isNotEmpty(chipId)){
                recvData.put("chipNumber",chipId);
                ApiResult result1 = this.doCommand20108(ApiConstant.UMBRELLA_MACHINE_COMMAND_20108,machineCode,code,message,recvData);
                result.setMessage(result.getMessage() + ApiConstant.CHIP_NUMBER_SEPARATOR + result1.getMessage());
            }
        }

        //还伞结果通知客户端
        if(account >0 ) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 物理还伞-还伞识别上报(二次交互模式)【20106】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20106(String command,String machineCode, int code, String message, JSONObject recvData){
        /**
         {
         "command": "20106",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "chipNumber": "111111",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"
         }
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_MACHINE_COMMAND_10107,machineCode, dataInfo);
        try {
            if(code == ApiResultConstant.SUCCESS.code){
                String chipNumber = recvData.getString("chipNumber");
                UmbrellaHardwareUmbrella umbrellaHardwareUmbrella = null;
                if(StringUtils.isNotEmpty(chipNumber)) {
                   umbrellaHardwareUmbrella = super.baseSelectUmbrellaHardwareUmbrellaNoCache(chipNumber);
                }
                //雨伞是我司雨伞
                if (umbrellaHardwareUmbrella != null) {
                    BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaUnReturnByChipNumber(chipNumber,true,"");
                    /**
                     {
                     "command": "10107",
                     "machineCode": "2018092700001",
                     "code": 1,
                     "message": "",
                     "data": {
                     "machineCode": "2018092700001",
                     "orderNo": "20180929100020001",
                     "chipNumber": "111111",
                     "dataPackage": {
                     "account": 10000004,
                     "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ-IJOIUEWRPOI"
                     }
                     }
                     }
                     */
                    if(businessOrderUmbrellaConsumption!=null) {
                        dataInfo.put("machineCode", machineCode);
                        if (businessOrderUmbrellaConsumption != null) {
                            dataInfo.put("orderNo", businessOrderUmbrellaConsumption.getOrderno());
                        } else {
                            dataInfo.put("orderNo", "");
                        }
                        dataInfo.put("chipNumber", chipNumber);
                        JSONObject dataPackage = new JSONObject();
                        if (businessOrderUmbrellaConsumption != null) {
                            dataPackage.put("orderNo", businessOrderUmbrellaConsumption.getOrderno());
                            dataPackage.put("account", businessOrderUmbrellaConsumption.getUserid());
                        } else {
                            dataPackage.put("orderNo", "");
                            dataPackage.put("account", "");
                        }
                        dataInfo.put("dataPackage", dataPackage);
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage(ApiResultConstant.SUCCESS.message);
                        result.setData(dataInfo);

                    }else{
                        LOGGER.error("物理还伞-还伞识别上报(二次交互模式)处理失败,雨伞chipNumber={}订单不存在,commandata={}",chipNumber,recvData.toJSONString());
                        result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                        result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                        result.setData(dataInfo);
                    }
                }else{
                    LOGGER.error("物理还伞-还伞识别上报(二次交互模式)失败,雨伞chipNumber={}不是我司雨伞,commandata={}",chipNumber,recvData.toJSONString());
                    result.setCode(ApiResultConstant.VERIFY_UMBRELLA_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_UMBRELLA_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }else{
                LOGGER.error("物理还伞-还伞识别上报(二次交互模式)业务处理失败,machineCode={}",machineCode);
                result.setCode(ApiResultConstant.FAILED.code);
                result.setMessage(ApiResultConstant.FAILED.message);
                result.setData(dataInfo);
            }
        }catch (Exception e){
            LOGGER.error("物理还伞-还伞识别上报(二次交互模式)【{}】异常,machineCode={},code={},message={},commandata={}",command,machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage(ApiResultConstant.FAILED.message);
            result.setData(dataInfo);
        }
        if(result!=null) {
            ApiResult machineResult = result;
            if(machineResult.getCode()!=ApiResultConstant.SUCCESS.code){
                machineResult.setCode(ApiResultConstant.FAILED.code);
                machineResult.setMessage(ApiResultConstant.FAILED.message);
            }
            //通知设备开启或关闭还伞模式
            if(machineResult.getCode()==ApiResultConstant.SUCCESS.code) {
                mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(machineResult), machineCode);
            }
        }
        return result;
    }
    /**
     * 物理还伞-还伞结果上报(二次交互模式)【20107】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20107(String command,String machineCode, int code, String message, JSONObject recvData){

        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30201,machineCode, dataInfo);
        int account = 0;
        try{
            if(code == ApiResultConstant.FAILED.code){
                LOGGER.error("物理还伞-还伞结果上报(二次交互模式)业务处理失败,machineCode={},commandata={}",machineCode,recvData.toJSONString());
                result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                result.setData(dataInfo);
            }
            //伞机业务处理成功
            else{
                /**
                 {
                 "command": "20107",
                 "machineCode": "2018092700001",
                 "code": 1,
                 "message": "",
                 "data": {
                 "orderNo": "20180929100020001",
                 "status": 9,
                 "pathCode": "path222222",
                 "pathNumber": 1,
                 "chipNumber": "111111",
                 "dataPackage": {
                 "account": 10000004,
                 "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
                 }
                 }
                 }
                 */
                dataInfo.put("orderNo", recvData.getString("orderNo"));
                dataInfo.put("dataPackage", recvData.getJSONObject("dataPackage"));

                String orderNo = JsonUtil.getString(recvData,"orderNo");
                String pathCode = JsonUtil.getString(recvData,"pathCode");
                int pathNumber = JsonUtil.getInteger(recvData,"pathNumber");
                String chipNumber = JsonUtil.getString(recvData,"chipNumber");
                Integer status = JsonUtil.getInteger(recvData,"status");
                dataInfo.put("faultStatus", status);

                JSONObject dataPackage = JsonUtil.getJSONObject(recvData,"dataPackage");
                account = JsonUtil.getInteger(dataPackage,"account");

                //查询订单
                BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = null;
                if(StringUtils.isNotEmpty(chipNumber)) {
                    businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaUnReturnByChipNumber(chipNumber, true, "");
                }
                if(businessOrderUmbrellaConsumption != null){
                    account = businessOrderUmbrellaConsumption.getUserid();
                    orderNo = businessOrderUmbrellaConsumption.getOrderno();
                    //更新订单信息
                    Date time = DateUtil.getNowDate();
                    //查询伞机
                    UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                    BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                    updateConsumption.setReturnMachineId(machineCode);
                    if(umbrellaHardwareMachine!=null){
                        updateConsumption.setReturnAdress(umbrellaHardwareMachine.getAddress());
                    }
                    updateConsumption.setReturnPathCode(pathCode);
                    updateConsumption.setReturnPathNumber(pathNumber);
                    updateConsumption.setReturnChipNumber(chipNumber);
                    //还伞成功
                    if(status==ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5);
                        updateConsumption.setEndtime(time);
                        updateConsumption.setFaultstatus(status);
                        //还伞失败
                    }else{
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
                        updateConsumption.setEndtime(time);
                        updateConsumption.setFaultstatus(status);
                    }
                    BusinessOrderUmbrellaConsumptionExample consumptionQueryExample= new BusinessOrderUmbrellaConsumptionExample();
                    BusinessOrderUmbrellaConsumptionExample.Criteria consumptionQueryCriteria = consumptionQueryExample.createCriteria();
                    //雨伞芯片ID
                    consumptionQueryCriteria.andChipNumberEqualTo(chipNumber);
                    //雨伞订单状态，包括已借出和还伞失败
                    consumptionQueryCriteria.andStatusBetween(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3,BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
                    int ret = super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionQueryExample);

                    if (status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9) {
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage("还伞成功");
                        //规避重复指令问题导致的伞机及伞道余量和用户借伞量的多算问题
                        if(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5 != businessOrderUmbrellaConsumption.getStatus() && BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6 != businessOrderUmbrellaConsumption.getStatus()) {
                            //更新伞机及伞道余量
                            super.updateUmbrellaMachineAndPathRemainder(machineCode, pathCode, pathNumber, 1);
                            //更新雨伞为/空闲/归还状态
                            if (StringUtils.isNotEmpty(chipNumber)) {
                                super.updateUmbrellaHardwareUmbrellaStatus(chipNumber, UmbrellaConstant.UM_UMBRELLA_STATUS_2,machineCode);
                            }
                            //结算计费
                            apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(orderNo, true, false, false);
                            //更新用户借伞状态
                            super.updateUserAccountUmbrellaStatus(account, -1);
                        }
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
                        result.setMessage("还伞失败");
                    }
                    dataInfo.put("faultStatus", status);
                    dataInfo.put("orderNo", orderNo);
                    result.setData(dataInfo);
                }else{
                    //订单不存在，如果上报红外切断也要变更伞机伞量
                    if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        //更新伞机及伞道余量
                        super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,1);
                    }
                    result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            LOGGER.error("物理还伞-还伞结果上报【{}】异常,machineCode={},code={},message={},commandata={}",command,machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage(ApiResultConstant.FAILED.message);
            result.setData(dataInfo);
        }
        //还伞结果通知客户端
        if(account>0) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 物理还伞上报(一次交互模式）【20108】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20108(String command,String machineCode, int code, String message, JSONObject recvData){

        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30201,machineCode, dataInfo);
        int account = 0;
        //上传的伞id集合
        List<String> resultChipNumList = new ArrayList<String>();
        //订单的伞id
        String orderChipNumber = "";
        String orderNo="";
        try{
            if(code == ApiResultConstant.FAILED.code){
                LOGGER.error("物理还伞上报(一次交互模式）业务处理失败,machineCode={},commandata={}",machineCode,recvData.toJSONString());
                result.setCode(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_BUSINESSFAIL.message);
                result.setData(dataInfo);
            }
            //伞机业务处理成功
            else{
                /**
                 {
                 "command": "20107",
                 "machineCode": "2018092700001",
                 "code": 1,
                 "message": "",
                 "data": {
                 "status": 9,
                 "pathCode": "path222222",
                 "pathNumber": 1,
                 "chipNumber": "111111"
                 }
                 }
                 */

                String pathCode = JsonUtil.getString(recvData,"pathCode");
                int pathNumber = JsonUtil.getInteger(recvData,"pathNumber");
                String chipNumber = JsonUtil.getString(recvData,"chipNumber");
                Integer status = JsonUtil.getInteger(recvData,"status");
                dataInfo.put("faultStatus", status);

                if(StringUtils.isNotEmpty(chipNumber)){
                    CollectionUtils.addAll(resultChipNumList,chipNumber.split(ApiConstant.CHIP_NUMBER_SEPARATOR));
                } else {
                    resultChipNumList.add("");
                }
                if(resultChipNumList.size() > 0){
                    chipNumber = resultChipNumList.get(0);
                    orderChipNumber = chipNumber;
                }

                //查询订单
                BusinessOrderUmbrellaConsumption businessOrderUmbrellaConsumption = null;
                if(StringUtils.isNotEmpty(chipNumber)) {
                    businessOrderUmbrellaConsumption = super.baseSelectBusinessOrderUmbrellaUnReturnByChipNumber(chipNumber,true,"");
                }
                if(businessOrderUmbrellaConsumption != null){
                    account = businessOrderUmbrellaConsumption.getUserid();
                    orderNo = businessOrderUmbrellaConsumption.getOrderno();
                    //更新订单信息
                    Date time = DateUtil.getNowDate();
                    //查询伞机
                    UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
                    BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                    updateConsumption.setReturnMachineId(machineCode);
                    if(umbrellaHardwareMachine!=null){
                        updateConsumption.setReturnAdress(umbrellaHardwareMachine.getAddress());
                    }
                    updateConsumption.setReturnPathCode(pathCode);
                    updateConsumption.setReturnPathNumber(pathNumber);
                    updateConsumption.setReturnChipNumber(chipNumber);
                    //还伞成功
                    if(status==ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_5);
                        updateConsumption.setEndtime(time);
                        updateConsumption.setFaultstatus(status);
                        //还伞失败
                    }else{
                        updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
                        updateConsumption.setEndtime(time);
                        updateConsumption.setFaultstatus(status);
                    }
                    BusinessOrderUmbrellaConsumptionExample consumptionQueryExample= new BusinessOrderUmbrellaConsumptionExample();
                    BusinessOrderUmbrellaConsumptionExample.Criteria consumptionQueryCriteria = consumptionQueryExample.createCriteria();
                    //雨伞芯片ID
                    consumptionQueryCriteria.andChipNumberEqualTo(chipNumber);
                    //雨伞订单状态，包括已借出和还伞失败
                    consumptionQueryCriteria.andStatusBetween(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3,BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_4);
                    int ret = super.updateBusinessOrderUmbrellaConsumption(updateConsumption,consumptionQueryExample);

                    if (status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9) {
                        result.setCode(ApiResultConstant.SUCCESS.code);
                        result.setMessage("还伞成功");
                        //更新伞机及伞道余量
                        super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,1);
                        //更新雨伞为/空闲/归还状态
                        if(StringUtils.isNotEmpty(chipNumber)) {
                            super.updateUmbrellaHardwareUmbrellaStatus(chipNumber, UmbrellaConstant.UM_UMBRELLA_STATUS_2,machineCode);
                        }
                        //更新用户借伞状态 //先更新在计费，否则会出现无法退预付金问题
                        super.updateUserAccountUmbrellaStatus(account,-1);
                        //结算计费
                        apiServerUmbrellaService.completeBusinessOrderUmbrellaConsumption(orderNo,true, false,false);
                    } else {
                        result.setCode(ApiResultConstant.FAILED.code);
                        result.setMessage("还伞失败");
                    }
                    dataInfo.put("faultStatus", status);
                    dataInfo.put("orderNo", orderNo);
                    result.setData(dataInfo);
                }else{
                    //订单不存在，如果上报红外切断也要变更伞机伞量
                    if(status == ApiConstant.MACHINE_COMMAND_RUNBACK_STATUS_9){
                        //更新伞机及伞道余量
                        super.updateUmbrellaMachineAndPathRemainder(machineCode,pathCode,pathNumber,1);
                    }
                    LOGGER.error("物理还伞上报(一次交互模式）订单不存在,machineCode={},commandata={}",machineCode,recvData.toJSONString());
                    result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            LOGGER.error("物理还伞上报(一次交互模式）【{}】异常,machineCode={},code={},message={},commandata={}",command,machineCode,code,message,recvData.toJSONString(),e);
            result.setCode(ApiResultConstant.FAILED.code);
            result.setMessage(ApiResultConstant.FAILED.message);
            result.setData(dataInfo);
        }
        for(String chipId : resultChipNumList){
            if(!orderChipNumber.equals(chipId) && StringUtils.isNotEmpty(chipId)){
                recvData.put("chipNumber",chipId);
                ApiResult result1 = this.doCommand20108(ApiConstant.UMBRELLA_MACHINE_COMMAND_20108,machineCode,code,message,recvData);
                result.setMessage(result.getMessage() + ApiConstant.CHIP_NUMBER_SEPARATOR + result1.getMessage());
            }
        }
        //还伞结果通知客户端
        if(account>0) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-进伞结果上报【20110】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20110(String command,String machineCode, int code, String message, JSONObject recvData){
        /**
         {
         "command": "20110",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "orderNo": "20180929100020001",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
         },
         "status": 10,
         "count": 3,
         "list": ["11111", "22222", "33333"]
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30601,machineCode, dataInfo);
        int account = 0;
        try {
            String orderNo = recvData.getString("orderNo");
            int status = recvData.getInteger("status");
            int count =recvData.getInteger("count");
            JSONArray array = recvData.getJSONArray("list");
            JSONObject dataPackage = JsonUtil.getJSONObject(recvData,"dataPackage");
            account = JsonUtil.getInteger(dataPackage,"account");
            dataInfo.put("orderNo", orderNo);
            dataInfo.put("dataPackage", dataPackage);

            //查询伞机
            UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
            //判断伞机状态
            if(umbrellaHardwareMachine == null){
                result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                result.setData(dataInfo);
            }else{

                //更新雨伞设备号
                super.updateUmbrellaAgentAndMachine(array.toJavaList(String.class),umbrellaHardwareMachine.getAgentId(),umbrellaHardwareMachine.getCode());
                //订单号
                UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                logExample.setOrderByClause("start_time desc");    //确保获取到最新的数据
                UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                //未删除
                logCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                logCriteria.andOrdernoEqualTo(orderNo);
                logCriteria.andMachineCodeEqualTo(machineCode);
                logCriteria.andEndTimeIsNull();
                logCriteria.andResultEqualTo(0);
                logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10110);
                UmbrellaHardwareManageLog log  = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                if(log != null){

                    Date endTime = DateUtil.getNowDate();
                    UmbrellaHardwareManageLog updateLog = new UmbrellaHardwareManageLog();
                    updateLog.setEndTime(endTime);
                    //正常
                    updateLog.setResult(Constant.CONST_FLAG_NORMAL);
                    updateLog.setUmbrellacount(count);
                    updateLog.setUmbrellalist(array.toJSONString());
                    UmbrellaHardwareManageLogExample updateExample = new UmbrellaHardwareManageLogExample();
                    updateExample.createCriteria().andIdEqualTo(log.getId());
                    umbrellaHardwareManageLogService.updateByExampleSelective(updateLog,updateExample);
                    //更新伞机雨伞数量
                   super.updateUmbrellaMachineAndPathRemainder(machineCode,"noPathCode",0,count);
                    //通知小程序,雨伞管理-进伞结果通知(mqtt)【30601】
                    /**
                     {
                     "command": 30601,
                     "machineCode": "2018092700001",
                     "code": 1,
                     "message": "",
                     "dataInfo": {
                     “orderNo":”20180929100020001",//交互订单
                     "count":10,
                     "dataPackage": {
                     "account": 10000004,
                     "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
                     }
                     }
                     }
                     */
                    result.setCode(ApiResultConstant.SUCCESS.code);
                    result.setMessage(ApiResultConstant.SUCCESS.message);
                    dataInfo.put("count",count);
                    result.setData(dataInfo);
                }else{
                    result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            LOGGER.error("雨伞管理-进伞结果上报【{}】异常,machineCode={},code={},message={}",machineCode,command,code,message,recvData.toJSONString(),e);
        }
        //进伞结果通知客户端
        if(account>0) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 雨伞管理-出伞结果上报【20112】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20112(String command,String machineCode, int code, String message, JSONObject recvData){
        /**
         {
         "command": "20112",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         "orderNo": "20180929100020001",
         "dataPackage": {
         "account": 10000004,
         "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
         },
         "status": 11,
         "count": 3,
         "list": ["11111", "22222", "33333"]
         }
         }
         */

        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.FAILED.code, ApiResultConstant.FAILED.message, ApiConstant.UMBRELLA_WECHATAPP_COMMAND_30701,machineCode, dataInfo);
        int account = 0;
        try {
            String orderNo = recvData.getString("orderNo");
            int status = recvData.getInteger("status");
            int count =recvData.getInteger("count");
            JSONArray array = recvData.getJSONArray("list");
            JSONObject dataPackage = JsonUtil.getJSONObject(recvData,"dataPackage");
            account = JsonUtil.getInteger(dataPackage,"account");
            dataInfo.put("count", count);
            dataInfo.put("orderNo", orderNo);
            dataInfo.put("dataPackage", dataPackage);

            //查询伞机
            UmbrellaHardwareMachine umbrellaHardwareMachine = super.baseSelectUmbrellaHardwareMachineNoCache(machineCode);
            //判断伞机状态
            if(umbrellaHardwareMachine == null){
                result.setCode(ApiResultConstant.VERIFY_MACHINE_UNENABLED.code);
                result.setMessage(ApiResultConstant.VERIFY_MACHINE_UNENABLED.message);
                result.setData(dataInfo);
            }else{
                //订单号
                UmbrellaHardwareManageLogExample logExample = new UmbrellaHardwareManageLogExample();
                logExample.setOrderByClause("start_time desc");    //确保获取到最新的数据
                UmbrellaHardwareManageLogExample.Criteria logCriteria = logExample.createCriteria();
                //未删除
                logCriteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
                logCriteria.andOrdernoEqualTo(orderNo);
                logCriteria.andMachineCodeEqualTo(machineCode);
                logCriteria.andEndTimeIsNull();
                logCriteria.andResultEqualTo(0);
                logCriteria.andCommandEqualTo(ApiConstant.UMBRELLA_MACHINE_COMMAND_10112);
                UmbrellaHardwareManageLog log = umbrellaHardwareManageLogService.selectFirstByExample(logExample);
                //操作日志存在
                if(log != null){
                    Date endTime = DateUtil.getNowDate();
                    UmbrellaHardwareManageLog updateLog = new UmbrellaHardwareManageLog();
                    updateLog.setEndTime(endTime);
                    //成功
                    updateLog.setResult(Constant.CONST_FLAG_NORMAL);
                    updateLog.setUmbrellacount(count);
                    updateLog.setUmbrellalist(array.toJSONString());
                    UmbrellaHardwareManageLogExample updateExample = new UmbrellaHardwareManageLogExample();
                    updateExample.createCriteria().andIdEqualTo(log.getId());
                    umbrellaHardwareManageLogService.updateByExampleSelective(updateLog,updateExample);

                    //更新伞机雨伞数量
                    super.updateUmbrellaMachineAndPathRemainder(machineCode,"noPathCode",0, -count);
                    /**
                     *
                     {
                     "command": 30701,
                     "machineCode": "2018092700001",
                     "code": 1,
                     "message": "",
                     "dataInfo": {
                     “orderNo":”20180929100020001",//交互订单
                     "count":10,
                     "dataPackage": {
                     "account": 10000004,
                     "token": "SDKJLJBB_JLKSDJFLKDSJFDSJFLJ - IJOIUEWRPOI"
                     }
                     }
                     }
                     */
                    result.setCode(ApiResultConstant.SUCCESS.code);
                    result.setMessage(ApiResultConstant.SUCCESS.message);
                    dataInfo.put("count",count);
                    result.setData(dataInfo);
                }else{
                    result.setCode(ApiResultConstant.VERIFY_ORDER_NOTEXIST.code);
                    result.setMessage(ApiResultConstant.VERIFY_ORDER_NOTEXIST.message);
                    result.setData(dataInfo);
                }
            }
        }catch (Exception e){
            LOGGER.error("雨伞管理-出伞结果上报【{}】异常,machineCode={},code={},message={}",machineCode,command,code,message,recvData.toJSONString(),e);
        }
        //出伞结果通知客户端
        if(account>0) {
            mq4UmbrellaWechatappNotify.send(JsonUtil.object2Json(result), String.valueOf(account));
        }
        return result;
    }
    /**
     * 心跳上报【20998】
     * @param command
     * @param machineCode
     * @param code
     * @param message
     * @param recvData
     */
    public ApiResult doCommand20998(String command,String machineCode, int code, String message, JSONObject recvData){
        /**
         {
         "command": "20998",
         "machineCode": "2018092700001",
         "code": 1,
         "message": "",
         "data": {
         }
         }
         */
        JSONObject dataInfo = new JSONObject();
        ApiResult result = new ApiResult(ApiResultConstant.SUCCESS.code, ApiResultConstant.SUCCESS.message,ApiConstant.UMBRELLA_MACHINE_COMMAND_10998, machineCode, dataInfo);
        try {
            //反馈消息给客户端
            mq4UmbrellaMachineNotify.send(JsonUtil.object2Json(result), machineCode);

            //查询机器是否离线
           //UmbrellaHardwareMachineExample example = new UmbrellaHardwareMachineExample();
           //UmbrellaHardwareMachineExample.Criteria criteria = example.createCriteria();
           ////机器码
           //criteria.andCodeEqualTo(machineCode);
           ////离线
           //criteria.andStatusEqualTo(UmbrellaConstant.UM_MACHINE_STATUS_3);
           ////未删除
           //criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);
           //UmbrellaHardwareMachine machine = super.baseSelectUmbrellaHardwareMachineByExample(example);
           //if(machine!=null){
           //    //更新状态为在线
           //    UmbrellaHardwareMachine newMachine = new UmbrellaHardwareMachine();
           //    newMachine.setStatus(UmbrellaConstant.UM_MACHINE_STATUS_2);
           //    super.updateUmbrellaHardwareMachine(newMachine,example);
           //}
        }catch (Exception e){
            LOGGER.error("心跳上报【{}】异常,machineCode={},code={},message={}",machineCode,command,code,message,recvData.toJSONString(),e);
        }
        return result;
    }
}
